package top.cwk.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import top.cwk.listener.SessionListener;
import top.cwk.model.customerPo.Customer;

/**
 * 
 * <p>Title: LoginInterceptor</p>
 * <p>Description:登录拦截器</p>
 * <p>Company: CHNI</p> 
 * @author chenwk
 * @date 2017年8月25日
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String path = request.getContextPath();
		Customer customer = (Customer) request.getSession().getAttribute("customer");
		if(customer!=null){
			//session存在该用户,检测是否sessionMap中是否是否匹配到当前登录的sessionid,
			//如果匹配到则不提示强制登录信息
			if(SessionListener.isContainsSessionID(request.getSession().getId())){
				//同一用户登录
				return true;
			}else{
				if(SessionListener.isContainsUsername(customer.getUsername())){
					//提示该用户被强制下线
					response.sendRedirect(path+"/customer/toLogin?forceLogout=1");
					return false;
				}else{
					request.setAttribute("isForceLogin", "true");
					return true;
				}
			}
		}else{
			//非法登录,或session超时
			response.sendRedirect(path+"/customer/toLogin");
			return false;
		}
		
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
